
echo "Setup server..."

aliyun configure set \
    --profile akProfile \
    --mode AK \
    --region ${ALIYUN_REGION_ID} \
    --access-key-id ${ALIYUN_DNS_ACCESS_KEY} \
    --access-key-secret ${ALIYUN_DNS_ACCESS_KEY_SECRET}

# apply once for the first time
# see: https://eff-certbot.readthedocs.io/en/stable/using.html
# and https://eff-certbot.readthedocs.io/en/stable/install.html
certbot certonly \
    --non-interactive \
    --agree-tos \
    --no-eff-email \
    --email ${CERTBOT_EMAIL} \
    --domains ${CERTBOT_DOMAIN} \
    --preferred-challenges dns \
    --manual \
    --manual-auth-hook "sh /usr/local/bin/alidns.sh" \
    --manual-cleanup-hook "sh /usr/local/bin/alidns.sh clean" \
    --deploy-hook "sh /opt/service/deploy-hook.sh"

# set cron jobs
# see https://serverfault.com/questions/790772/best-practices-for-setting-a-cron-job-for-lets-encrypt-certbot-renewal
# trigger on 13:30 and 02:30 with timezone Asian/Shanghai
printf "$CERTBOT_AUTO_RENEW_CRON " >> /etc/crontabs/root
printf '%s'\
    'certbot renew ' \
    '--manual --preferred-challenges dns ' \
    '--manual-auth-hook "sh /usr/local/bin/alidns.sh" ' \
    '--manual-cleanup-hook "sh /usr/local/bin/alidns.sh clean" ' \
    '--deploy-hook "sh /opt/service/deploy-hook.sh"' \
    >> /etc/crontabs/root
printf '\n' >> /etc/crontabs/root

# enable cron jobs at foreground
crond -f